﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using System.Web.Security;
using MinistryStandardPlatformBusiness.MessagePool.Entity;
using MinistryStandardPlatformEntity;
using MinistryStandardPlatformWeb.Controllers.RealTime;
using MinistryStandardPlatformWeb.Models;
using Newtonsoft.Json;

namespace MinistryStandardPlatformWeb.Controllers
{
    [IsLogin(Order = 0)]
    public class MonitorCenterController : Controller
    {
        private MSPDataContext context = new MSPDataContext();
        private string strLogFilePath = "E:\\WebLog\\GpsDataLog.txt";
        //
        // GET: /MonitorCenter/

        public ActionResult Index(string id)
        {
            //这是进入网站时默认加载监控中心的情况，如果该用户没有监控中心的权限，需要导航到别处
            if (id == "default" && !CommonFunctions.GetLoginUser().HasMenuRight("1"))
            {
                MenuRights menu = context.MenuRights.Where(m => m.UserId == CommonFunctions.GetLoginUser().UserId).OrderBy(m => m.MenuId).FirstOrDefault();
                if (menu == null)
                {
                    FormsAuthentication.SignOut();
                    Response.Write("<script>alert('当前账号不具备任何菜单权限'); window.location.href='/Login/Login';</script>");
                    //return RedirectToAction("Login", "Login");
                }
                else
                {
                    string controller = "";
                    switch (menu.MenuId)
                    {
                        case "2":
                            controller = "DispatchCenter";
                            break;
                        case "3":
                            controller = "OperationManage";
                            break;
                        case "4":
                            controller = "ReportCenter";
                            break;
                        case "5":
                            controller = "SystemManage";
                            break;
                    }
                    return RedirectToAction("Index", controller);
                }
            }
            return View();
        }

        [MenuAuthorized("1", Order = 1)]
        public ActionResult Tree()
        {
            //LoginUsers loginUser = new LoginUsers();
            //loginUser.UserId = CommonFunctions.GetLoginUser().UserId;
            //List<ZTreeNode> vehicleRight = this.GetVehicleRights(loginUser);
            //List<RealTimeModel> vehicleBasic = this.GetVehicleBasicInfoList(loginUser);
            //ViewBag.vehicleRight = CommonFunctions.ListToJsonStr(vehicleRight);
            //ViewBag.vehicleBasic = CommonFunctions.ListToJsonStr(vehicleBasic);
            return PartialView();
        }

        [MenuAuthorized("1", Order = 1)]
        public ActionResult Map()
        {
            return PartialView();
        }
        //车辆信息提示窗口
        [MenuAuthorized("1", Order = 1)]
        public ActionResult GetVehicleInfo(string vehicleNum)
        {
            InfoVehicle infoVehicle = this.context.InfoVehicle.Where(t => t.Vehiclenum == vehicleNum).First();

            ViewBag.VehicleInfo = infoVehicle;
            ViewBag.GpsTypeName = this.context.Dictionary_Detail.Where(t => t.TypeID == "gpstype" && t.DicValue == infoVehicle.GPSType.ToString()).First().DicName;
            ViewBag.GpsVersionName = this.context.Dictionary_Detail.Where(t => t.Memo == infoVehicle.GPSType.ToString() && t.TypeID == "gpsversion" && t.DicValue == infoVehicle.GPSVersion.ToString()).First().DicName;
            ViewBag.VehicleDepart = this.context.InfoUnit.Where(t => t.UNITID == infoVehicle.ParentUnitId).First().UNITNAME;
            string tmpStr = "";
            if (infoVehicle.VehiclecurState == 0)
            {
                tmpStr = "正常";
            }
            else if (infoVehicle.VehiclecurState == 1)
            {
                tmpStr = "临时";
            }
            else//2
            {
                tmpStr = "维修";
            }
            ViewBag.VehicleState = tmpStr;
            if (infoVehicle.VehiclecurState == 0)
            {
                tmpStr = "无任务";
            }
            else if (infoVehicle.VehiclecurState == 1)
            {
                tmpStr = "任务中";
            }
            else if (infoVehicle.VehiclecurState == 2)
            {
                tmpStr = "维修中";
            }
            else//3
            {
                tmpStr = "无任务离场";
            }
            ViewBag.VehicleTask = tmpStr;
            return View();
        }
        //历史轨迹
        [MenuAuthorized("1", Order = 1)]
        public ActionResult VehicleHistory(string vehicleNum)
        {
            ViewBag.InfoModel = CommonFunctions.ObjectToJsonStr<RealTimeModel>(this.GetVehicleBasicInfoById(vehicleNum));
            return View();
        }
        //车辆跟踪
        [MenuAuthorized("1", Order = 1)]
        public ActionResult VehicleTrack(string vehicleNum)
        {
            ViewBag.InfoModel = CommonFunctions.ObjectToJsonStr<RealTimeModel>(this.GetVehicleBasicInfoById(vehicleNum));
            return View();
        }

        //[MenuAuthorized("1", Order = 1)]
        public JsonResult GetVehicles()
        {
            LoginUsers loginUser = new LoginUsers();
            loginUser.UserId = CommonFunctions.GetLoginUser().UserId;
            List<ZTreeNode> vehicles = this.GetVehicleRights(loginUser);
            return Json(vehicles, JsonRequestBehavior.AllowGet);
        }

        // [MenuAuthorized("1", Order = 1)]
        public ActionResult GetVehiclesBasicInfo()
        {
            LoginUsers loginUser = new LoginUsers();
            loginUser.UserId = CommonFunctions.GetLoginUser().UserId;
            List<RealTimeModel> vehicles = this.GetVehicleBasicInfoList(loginUser);
            return Json(vehicles, JsonRequestBehavior.AllowGet);
        }
        //通过车辆id获取车辆基础信息
        [MenuAuthorized("1", Order = 1)]
        private RealTimeModel GetVehicleBasicInfoById(string vehicleNum)
        {
            RealTimeModel model = (from t in this.context.InfoVehicle
                                   where t.Vehiclenum == vehicleNum
                                   select new RealTimeModel()
                                   {
                                       id = t.Vehiclenum,
                                       name = t.VehicleId,
                                       sim = t.SIM,
                                       depart = t.InfoUnit.UNITNAME
                                   }).First();
            return model;
        }
        //获取车辆的基础信息
        [MenuAuthorized("1", Order = 1)]
        private List<RealTimeModel> GetVehicleBasicInfoList(LoginUsers loginUser)
        {
            List<RealTimeModel> vehicleList = null;
            if (!string.IsNullOrEmpty(loginUser.UserId))
            {
                vehicleList = (from t in this.context.InfoVehicle
                               join r in this.context.RightsDetails
                               on t.Vehiclenum equals r.NodeId
                               where r.UserId == loginUser.UserId
                               select new RealTimeModel()
                               {
                                   id = t.Vehiclenum,
                                   name = t.VehicleId,
                                   sim = t.SIM,
                                   depart = t.InfoUnit.UNITNAME
                               }).ToList();

                //第一次获取gps信息
                List<string> simList = new List<string>();
                for (int i = 0; i < vehicleList.Count; i++)
                {
                    simList.Add(vehicleList[i].sim);
                }
                List<LatestGpsInfo> tmpGpsList = RealTimeGet.getRealtimeGPSinfoBySim(simList);
                for (int i = 0; i < vehicleList.Count; i++)
                {
                    RealTimeModel basicItem = vehicleList[i];
                    for (int j = 0; j < tmpGpsList.Count; j++)
                    {
                        LatestGpsInfo item = tmpGpsList[j];
                        if (basicItem.sim.Equals(item.SimId))
                        {
                            basicItem.sim = item.SimId;
                            basicItem.lat = item.Nlatitude;
                            basicItem.lng = item.Nlongitude;
                            basicItem.addr = item.Poi;
                            basicItem.dire = CommonFunctions.TranslateDirection(item.Direction);
                            basicItem.gpsMileage = this.DoubleTo2Str(item.GpsDistance);
                            basicItem.gpsSpeed = this.DoubleTo2Str(item.Speed);
                            basicItem.devMileage = this.DoubleTo2Str(item.Distance);
                            basicItem.devSpeed = this.DoubleTo2Str(item.DevSpeed);
                            basicItem.oil = this.DoubleTo2Str(item.AttachOil);
                            basicItem.time = item.UpTime;
                            basicItem.battery = item.battery;
                            CommonFunctions.ParseWarnInfo(basicItem, item.WarnSign);
                            CommonFunctions.ParseStateInfo(basicItem, item.StatusSign);
                            break;
                        }
                    }
                }
            }
            return vehicleList;
        }
        //获取用户单位和车辆权限
        [MenuAuthorized("1", Order = 1)]
        private List<ZTreeNode> GetVehicleRights(LoginUsers loginUser)
        {//loginUser权限授予者，rightUser权限接受者
            List<RightsDetails> rights = null;
            List<ZTreeNode> nodes = null;
            if (!string.IsNullOrEmpty(loginUser.UserId))
            {
                nodes = (from r in this.context.RightsDetails
                         join t in this.context.InfoVehicle
                         on r.NodeId equals t.Vehiclenum
                         into rt
                         from rtd in rt.DefaultIfEmpty()
                         where r.UserId == loginUser.UserId
                         select new ZTreeNode()
                         {
                             id = r.NodeId,
                             name = r.NodeName,
                             pId = r.ParentNodeId,
                             sim = rtd.SIM,
                             icon = (r.NodeTYPE == true ? "true" : "false"),
                             others = rtd.GPSType.ToString()
                         }).ToList();
                //rights = this.context.RightsDetails.Where(t => t.UserId == loginUser.UserId).ToList();
            }
            if (nodes != null)
            {
                for (int i = 0; i < nodes.Count; i++)
                {
                    ZTreeNode node = nodes[i];
                    if (node.icon == "true")
                    {//单位
                        node.icon = "/Content/themes/zTreeStyle/img/diy/1_open.png";
                    }
                    else
                    {//车
                        if (!node.others.Equals("5"))
                        {
                            node.icon = "/Content/themes/zTreeStyle/img/diy/car.png";
                        }
                        else
                        {
                            node.icon = "/Content/themes/zTreeStyle/img/diy/10.png";
                        }
                        //获取车辆在线状态
                        List<string> tmpSimList = new List<string>();
                        tmpSimList.Add(node.sim);
                        List<LatestGpsInfo> tmpGpsList = RealTimeGet.getRealtimeGPSinfoBySim(tmpSimList);
                        for (int j = 0; j < tmpGpsList.Count; j++)
                        {
                            LatestGpsInfo item = tmpGpsList[j];
                            if (!string.IsNullOrEmpty(item.StatusSign) && item.StatusSign.Length >= 1)
                            {
                                node.icon = CommonFunctions.GetVehicleIcon(item.UpTime, item.StatusSign[0].ToString());
                            }
                        }
                    }
                }
            }
            //if (rights != null)
            //{
            //    nodes = new List<ZTreeNode>();
            //    foreach (RightsDetails right in rights)
            //    {
            //        ZTreeNode node = new ZTreeNode();
            //        if (right.NodeTYPE == true)
            //        {//单位
            //            node.icon = "/Content/themes/zTreeStyle/img/diy/1_open.png";
            //        }
            //        else
            //        {//车
            //            node.icon = "/Content/themes/zTreeStyle/img/diy/car.png";
            //        }
            //        nodes.Add(node);
            //    }
            //}
            return nodes;
        }
        //获取Gps数据
        [HttpPost]
        [MenuAuthorized("1", Order = 1)]
        public ActionResult GetGpsData(List<string> sims, List<string> times)
        {
            if (sims != null && times != null && sims.Count != 0 && sims.Count == times.Count)
            {

                //测试获取gps数据
                //List<LatestGpsInfo> list = new List<LatestGpsInfo>();
                //LatestGpsInfo tmp = new LatestGpsInfo();
                //tmp.SimId = "868487002127280";
                //tmp.Nlatitude = "28.27345295";
                //tmp.Nlongitude = "112.5506864";
                //tmp.Poi = "湖南省长沙市宁乡县亿佰家文具总汇;新康中路";
                //tmp.Direction = "0";
                //tmp.GpsDistance = "-1";
                //tmp.Speed = "0.4";
                //tmp.Distance = "";
                //tmp.DevSpeed = "";
                //tmp.Oil = "-1";
                //tmp.UpTime = "2014-08-20 17:00:35";
                //tmp.battery = "92";
                //tmp.WarnSign = "";
                //tmp.StatusSign = "";
                //list.Add(tmp);
                /////////////////////////////////////////////////////////////////////
                //正常获取gps数据
                List<LatestGpsInfo> list = RealTimeGet.getRealtimeGPSinfoBySim(sims);
                this.WriteLog(list);
                /////////////////////////////////////////////////////////////////////
                //只有有最新gps信息的车辆才回传到前端
                List<RealTimeModel> modelList = new List<RealTimeModel>();
                for (int k = 0; k < list.Count; k++)
                {
                    LatestGpsInfo item = list[k];
                    if (item.SimId.Length == 11)
                    {
                        item.SimId = "0" + item.SimId;
                    }
                    for (int i = 0; i < sims.Count; i++)
                    {
                        if (item.SimId.Equals(sims[i]))
                        {
                            if (item.UpTime.CompareTo(times[i]) > 0)
                            {
                                RealTimeModel model = new RealTimeModel();
                                model.sim = item.SimId;
                                model.lat = item.Nlatitude;
                                model.lng = item.Nlongitude;
                                model.addr = item.Poi;
                                model.dire = CommonFunctions.TranslateDirection(item.Direction);
                                model.gpsMileage = this.DoubleTo2Str(item.GpsDistance);
                                model.gpsSpeed = this.DoubleTo2Str(item.Speed);
                                model.devMileage = this.DoubleTo2Str(item.Distance);
                                model.devSpeed = this.DoubleTo2Str(item.DevSpeed);
                                model.oil = this.DoubleTo2Str(item.AttachOil);
                                model.time = item.UpTime;
                                model.battery = item.battery;
                                CommonFunctions.ParseWarnInfo(model, item.WarnSign);
                                CommonFunctions.ParseStateInfo(model, item.StatusSign);
                                modelList.Add(model);
                            }
                            break;
                        }
                    }
                }
                var json = new
                {
                    total = modelList.Count,
                    rows = (from r in modelList
                            select r).ToArray()
                };
                var serializer = new JavaScriptSerializer();
                serializer.MaxJsonLength = Int32.MaxValue;
                return Content(serializer.Serialize(json), "application/json");
            }
            return null;
        }

        //获取历史Gps数据
        [HttpPost]
        [MenuAuthorized("1", Order = 1)]
        public ActionResult GetHistoryGpsData(string beginTime, string endTime, string vehicleNum)
        {
            if (!string.IsNullOrEmpty(beginTime) && !string.IsNullOrEmpty(endTime) && !string.IsNullOrEmpty(vehicleNum))
            {
                string sql = "select simid sim,"
                + "cast(cast(longitudeoffset as decimal(20,8)) as varchar(20)) lng,"
                + "cast(cast(latitudeoffset as decimal(20,8)) as varchar(20)) lat,"
                + "cast(direction as varchar(10)) dire,"
                + "cast(speed as varchar(10)) gpsSpeed,"
                + "cast(devspeed as varchar(10)) devSpeed,"
                + "cast(gpsmileage as varchar(10)) gpsMileage,"
                + "cast(mileage as varchar(10)) devMileage,"
                + "cast(attachoil as varchar(10)) oil,"
                + "recordtime as time,"
                + "warninfo as warn,"
                + "statusinfo as state "
                + "from gpsbasic "
                + "where recordtime >= '" + beginTime + "' and recordtime <= '" + endTime + "' and vehicleNum = '" + vehicleNum + "' "
                + "order by recordtime asc";
                string historyStr = RealTimeGet.getReportFromGeoBase(
                    CommonFunctions.GetLoginUser().UserId,
                    sql,
                    beginTime,
                    endTime,
                    "0");
                List<RealTimeModel> modelList = new List<RealTimeModel>();
                if (historyStr != "error" && historyStr != "")
                {
                    try
                    {
                        modelList = CommonFunctions.JsonStrToObject<List<RealTimeModel>>(historyStr);
                        MinistryStandardPlatformBusiness.DBService.DBHelperClient geoHelper = new MinistryStandardPlatformBusiness.DBService.DBHelperClient();
                        for (int i = 0; i < modelList.Count; i++)
                        {
                            RealTimeModel model = modelList[i];
                            model.dire = CommonFunctions.TranslateDirection(model.dire);
                            CommonFunctions.ParseWarnInfo(model, model.warn);
                            CommonFunctions.ParseStateInfo(model, model.state);
                            //if (i < 20)
                            //{
                            //    model.addr = geoHelper.GgpsTranslate2BaiduPoi(model.lng, model.lat);
                            //}
                        }
                    }
                    catch (Exception e)
                    {
                        return null;
                    }
                }
                else
                {
                }
                var json = new
                {
                    total = modelList.Count,
                    rows = (from r in modelList
                            select r).ToArray()
                };
                var serializer = new JavaScriptSerializer();
                serializer.MaxJsonLength = Int32.MaxValue;
                return Content(serializer.Serialize(json), "application/json");
            }
            return null;
        }

        [HttpPost]
        /*获取区域*/
        [MenuAuthorized("1", Order = 1)]
        public ActionResult GetRegions()
        {
            string userId = CommonFunctions.GetLoginUser().UserId;
            List<RegionInfo> list = (from t in this.context.InfoRegion
                                     join r in this.context.RightsDetails
                                     on t.unitId equals r.NodeId
                                     where r.UserId == userId && r.HasRight == true
                                     select new RegionInfo()
                                     {
                                         mId = t.regId,
                                         mName = t.regName,
                                         mLat = t.regLatitude.ToString(),
                                         mLng = t.regLongitude.ToString(),
                                         mRadius = t.regRadius.ToString()
                                     }).ToList();
            var json = new
            {
                total = list.Count,
                rows = (from r in list
                        select r).ToArray()
            };
            var serializer = new JavaScriptSerializer();
            serializer.MaxJsonLength = Int32.MaxValue;
            return Content(serializer.Serialize(json), "application/json");
        }

        [HttpPost]
        /*基站定位*/
        [MenuAuthorized("1", Order = 1)]
        public ActionResult StationLocation(string sim)
        {
            bool ret = RealTimeSend.CellLocationApp(sim);
            var json = new
            {
                ret = ret
            };
            return Json(json);
        }
        //基站定位，批量
        [MenuAuthorized("1", Order = 1)]
        public ActionResult DepartStationLocation(string departId)
        {
            List<String> list = (from t in this.context.InfoVehicle
                                 from r in this.context.RightsDetails
                                 where r.UserId == CommonFunctions.GetLoginUser().UserId
                                 && r.ParentNodeId == departId
                                 && r.NodeTYPE == false
                                 && t.Vehiclenum == r.NodeId
                                 && t.GPSType == 5
                                 select t.SIM).ToList();
            String sims = "";
            for (int i = 0; i < list.Count; i++)
            {
                if (i == list.Count - 1)
                {
                    sims += list[i];
                }
                else
                {
                    sims += list[i] + ";";
                }
            }
            bool ret = RealTimeSend.CellLocationApp(sims);
            var json = new
            {
                ret = ret
            };
            return Json(json);
        }
        /*解析地理位置*/
        [HttpPost]
        [MenuAuthorized("1", Order = 1)]
        public ActionResult ParseAddr(string key, int page, List<string> lngs, List<string> lats)
        {//key为查询批次的唯一标示，防止前台点击“查询”重新查询另一批数据时，后台处理返回数据与前台数据不唯一
            if (lngs.Count == lats.Count)
            {
                MinistryStandardPlatformBusiness.DBService.DBHelperClient geoHelper = new MinistryStandardPlatformBusiness.DBService.DBHelperClient();
                List<string> pois = new List<string>();
                for (int i = 0; i < lngs.Count; i++)
                {
                    pois.Add(geoHelper.GgpsTranslate2BaiduPoi(lngs[i], lats[i]));
                }
                var json = new
                {
                    key = key,
                    page = page,
                    pois = (from r in pois
                            select r).ToArray()
                };
                return Json(json);
            }
            return null;
        }

        /*string double转为2为小数 string*/
        [MenuAuthorized("1", Order = 1)]
        public string DoubleTo2Str(string str)
        {
            if (!string.IsNullOrEmpty(str))
            {
                if (str == "0")
                {
                    return "0";
                }
                else
                {
                    try
                    {
                        string d = Convert.ToDouble(str).ToString("0.00");
                        if (d.Equals("0.00"))
                        {
                            return "0";
                        }
                        return d;
                    }
                    catch
                    {
                        return "";
                    }
                }
            }
            return "";
        }


        /*写日志*/
        [MenuAuthorized("1", Order = 1)]
        private void WriteLog(List<LatestGpsInfo> list)
        {
            if (!System.IO.File.Exists(strLogFilePath))
            {
                System.IO.File.Create(strLogFilePath);
            }
            else
            {
                System.IO.FileInfo file = new FileInfo(strLogFilePath);
                if (file.Length >= 1024 * 1024 * 200)
                {//大于200M清楚日志
                    System.IO.File.Delete(strLogFilePath);
                    System.IO.File.Create(strLogFilePath);
                }
            }
            StreamWriter logWriter = System.IO.File.AppendText(strLogFilePath);
            for (int i = 0; i < list.Count; i++)
            {
                LatestGpsInfo item = list[i];
                string log = "[sim:" + item.SimId
                           + ",lat:" + item.Nlatitude
                           + ",lng:" + item.Nlongitude
                           + ",addr:" + item.Poi
                           + ",dire:" + item.Direction
                           + ",gpsMileage:" + item.GpsDistance
                           + ",gpsSpeed:" + item.Speed
                           + ",devMileage:" + item.Distance
                           + ",devSpeed:" + item.DevSpeed
                           + ",attachoOil:" + item.AttachOil
                           + ",oil" + item.Oil
                           + ",time:" + item.UpTime
                           + ",battery:" + item.battery
                           + ",warn:" + item.WarnSign
                           + ",status:" + item.StatusSign + "]";
                logWriter.WriteLine(log);
            }
            logWriter.Close();
        }

        [HttpPost]
        [MenuAuthorized("1", Order = 1)]
        public ActionResult ExportExcel()
        {
            String name = Request.Form["name"];
            String sim = Request.Form["sim"];
            String depart = Request.Form["depart"];
            String gps = Request.Form["data"];
            List<HistoryExcel> list = CommonFunctions.JsonStrToObject<List<HistoryExcel>>(gps);
            var sbHtml = new System.Text.StringBuilder();
            sbHtml.Append("<table border='1' cellspacing='0' cellpadding='0'>");
            sbHtml.Append("<tr>");
            var lstTitle = new List<string> { "序号", "车牌号", "SIM卡号", "所属单位", "经度", "纬度", "地址", "GPS速度", "GPS里程", "仪表速度", "仪表里程", "油量", "ACC", "正反转", "方向", "上传时间" };
            foreach (var item in lstTitle)
            {
                sbHtml.AppendFormat("<td style='font-size: 14px;text-align:center;background-color: #DCE0E2; font-weight:bold;' height='25'>{0}</td>", item);
            }
            sbHtml.Append("</tr>");

            for (int i = 0; i < list.Count; i++)
            {
                sbHtml.Append("<tr>");
                sbHtml.AppendFormat("<td>{0}</td>", i + 1);
                sbHtml.AppendFormat("<td>{0}</td>", name);
                sbHtml.AppendFormat("<td style='vnd.ms-excel.numberformat:@;'>{0}</td>", sim);
                sbHtml.AppendFormat("<td>{0}</td>", depart);
                sbHtml.AppendFormat("<td>{0}</td>", list[i].lng);
                sbHtml.AppendFormat("<td>{0}</td>", list[i].lat);
                sbHtml.AppendFormat("<td>{0}</td>", list[i].addr);
                sbHtml.AppendFormat("<td>{0}</td>", list[i].gpsSpeed);
                sbHtml.AppendFormat("<td>{0}</td>", list[i].gpsMileage);
                sbHtml.AppendFormat("<td>{0}</td>", list[i].devSpeed);
                sbHtml.AppendFormat("<td>{0}</td>", list[i].devMileage);
                sbHtml.AppendFormat("<td>{0}</td>", list[i].oil);
                sbHtml.AppendFormat("<td>{0}</td>", list[i].acc);
                sbHtml.AppendFormat("<td>{0}</td>", list[i].reverse);
                sbHtml.AppendFormat("<td>{0}</td>", list[i].dire);
                sbHtml.AppendFormat("<td>{0}</td>", list[i].time);
                sbHtml.Append("</tr>");
            }
            sbHtml.Append("</table>");

            //第一种:使用FileContentResult
            byte[] fileContents = System.Text.Encoding.Default.GetBytes(sbHtml.ToString());
            return File(fileContents, "application/ms-excel", name + "_" + sim + "历史轨迹.xls");

            ////第二种:使用FileStreamResult
            //var fileStream = new MemoryStream(fileContents);
            //return File(fileStream, "application/ms-excel", "fileStream.xls");

            ////第三种:使用FilePathResult
            ////服务器上首先必须要有这个Excel文件,然会通过Server.MapPath获取路径返回.
            //var fileName = Server.MapPath("~/Files/fileName.xls");
            //return File(fileName, "application/ms-excel", "fileName.xls");
            //return null;
        }

        [HttpPost]
        [MenuAuthorized("1", Order = 1)]
        public ActionResult ExportStopExcel()
        {
            String name = Request.Form["name"];
            String sim = Request.Form["sim"];
            String depart = Request.Form["depart"];
            String stop = Request.Form["data"];
            List<StopExcel> list = CommonFunctions.JsonStrToObject<List<StopExcel>>(stop);
            var sbHtml = new System.Text.StringBuilder();
            sbHtml.Append("<table border='1' cellspacing='0' cellpadding='0'>");
            sbHtml.Append("<tr>");
            var lstTitle = new List<string> { "序号", "车牌号", "SIM卡号", "所属单位", "开始时间", "结束时间", "停车时长", "停车地点" };
            foreach (var item in lstTitle)
            {
                sbHtml.AppendFormat("<td style='font-size: 14px;text-align:center;background-color: #DCE0E2; font-weight:bold;' height='25'>{0}</td>", item);
            }
            sbHtml.Append("</tr>");

            for (int i = 0; i < list.Count; i++)
            {
                sbHtml.Append("<tr>");
                sbHtml.AppendFormat("<td>{0}</td>", i + 1);
                sbHtml.AppendFormat("<td>{0}</td>", name);
                sbHtml.AppendFormat("<td style='vnd.ms-excel.numberformat:@;'>{0}</td>", sim);
                sbHtml.AppendFormat("<td>{0}</td>", depart);
                sbHtml.AppendFormat("<td>{0}</td>", list[i].startTime);
                sbHtml.AppendFormat("<td>{0}</td>", list[i].endTime);
                sbHtml.AppendFormat("<td>{0}</td>", list[i].interval);
                sbHtml.AppendFormat("<td>{0}</td>", list[i].addr);
                sbHtml.Append("</tr>");
            }
            sbHtml.Append("</table>");

            //第一种:使用FileContentResult
            byte[] fileContents = System.Text.Encoding.Default.GetBytes(sbHtml.ToString());
            return File(fileContents, "application/ms-excel", name + "_" + sim + "停车地点.xls");

            ////第二种:使用FileStreamResult
            //var fileStream = new MemoryStream(fileContents);
            //return File(fileStream, "application/ms-excel", "fileStream.xls");

            ////第三种:使用FilePathResult
            ////服务器上首先必须要有这个Excel文件,然会通过Server.MapPath获取路径返回.
            //var fileName = Server.MapPath("~/Files/fileName.xls");
            //return File(fileName, "application/ms-excel", "fileName.xls");
            //return null;
        }
    }
}
